package sort;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-01-15
 * Time: 21:33
 */
public class MergeSort {
    public static void main(String[] args) {

        int[] arr = {2, 1, 32, 1, 32, 1, 32, 1, 3};
        mergeSortNor(arr);
        System.out.println(Arrays.toString(arr));
    }

    //归并排序（典型的分治法）
    public static void mergeSort(int[] arr) {
        mergeSort(arr, 0, arr.length - 1);
    }

    private static void mergeSort(int[] arr, int left, int right) {
        if (left >= right) {
            return;
        }
        int mid = left + (right - left) / 2;
        //分
        mergeSort(arr, left, mid);
        mergeSort(arr, mid + 1, right);
        //合
        merge(arr, left, right, mid);
    }

    private static void merge(int[] arr, int left, int right, int mid) {
        int s1 = left;
        int s2 = mid + 1;
        int[] temp = new int[right - left + 1];//开辟临时数组
        int k = 0;//temp的初始下标
        while (s1 <= mid && s2 <= right) {
            if (arr[s1] <= arr[s2]) {
                temp[k++] = arr[s1++];
            } else {
                temp[k++] = arr[s2++];
            }
        }
        while (s1 <= mid) {
            temp[k++] = arr[s1++];
        }
        while (s2 <= right) {
            temp[k++] = arr[s2++];
        }
        System.arraycopy(temp, 0, arr, left, temp.length);
    }

    //非递归法
    public static void mergeSortNor(int[] arr) {
        int len = arr.length;
        int gap = 1;//步长用来划分合并数组
        while (gap < len) {
            for (int i = 0; i < len; i += 2 * gap) {
                int left = i;
                int mid = left + gap - 1;
                int right = mid + gap;
                if (mid >= len) {
                    mid = len - 1;
                }
                if (right >= len) {
                    right = len - 1;
                }
                merge(arr, left, right, mid);
            }
            gap *= 2;
        }
    }
}
